import axios from "axios";
import store from "@/store/index"
const instance = axios.create({
    baseURL: "/api",
    timeout: 5000
})

instance.interceptors.request.use(config => {

    let token = localStorage.getItem("x-auth-token")
    if (token) {
        config.headers["x-auth-token"] = token;
    }

    return config
}, err => {
    return Promise.reject(err)
})

instance.interceptors.response.use(res => {  //后端如果没有设置状态码,默认是200,状态码为200,请求失败的话,会执行这里
    let ret = res.data;
    // console.log(ret.errCode);
    if (ret.errCode !== 0) {
        // 提示
        alert(ret.message);
    }
    return ret
}, err => {  //后端是可以设置400和500的状态码,如果设置了500,就会执行这里.
    // alert(err.response.data.message);

    let action = {
        type: "showAlert",
        value: {
            showAlert: true,
            alertType: "warning",
            alertContent: err.response.data.message
        }
    }
    store.dispatch(action)

    setTimeout(() => {
        store.dispatch({
            type:"hideAlert"
        })
    }, 1500)
    // 如果登录失效,把err返回出去,让home里面的res接收 res接收之后,再做逻辑判断
    if(err.response.data.errCode===1002){
        return err
    }
    return Promise.reject(err)
})

export default instance